package dao;

import application.exceptions.ItemNotFoundException;
import mappings.Standards;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utils.HibernateUtil;

import java.util.List;

@SuppressWarnings("JpaQlInspection")
public class StandardsDao
{
    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public List<Standards> getAllStandards()
    {
        Session session = sessionFactory.openSession();

        List<Standards> standards = session.createCriteria(Standards.class)
                .list();

        session.close();

        return standards;
    }

    public Standards addStandards(String name)
    {
        Standards standards = new Standards();
        standards.setName(name);

        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        session.save(standards);

        tx.commit();
        session.close();

        return standards;
    }

    public Standards editStandard(Integer id, Standards standard) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        Standards standardToEdit = (Standards) session.get(Standards.class, id);

        if(standardToEdit == null)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        standardToEdit.setName(standard.getName());
        session.update(standardToEdit);
        tx.commit();
        session.close();

        return standardToEdit;
    }

    public void deleteStandard(Integer id) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        int affectedRows = session.createQuery("delete Standards where id = :id")
                .setParameter("id", id)
                .executeUpdate();

        if(affectedRows == 0)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        tx.commit();
        session.close();
    }
}
